<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * @func: 获取登录用户信息
 * @return: array
 */
function getSessionUser() {
	return unserialize($_SESSION ['mdd_user']);
}

/**
 * @func: 获取登录的用户编号
 * @return: number
 */
function getSessionUserId() {
	$user = getSessionUser();	
	return $user ['id'];
}

/**
 * @func: 获取登录美容师信息
 * @return: array
 */
function getBeautician() {
	return unserialize($_SESSION['beautician']);	                              
}

/**
 * @func: 获取美容师编号
 * @return: number
 */
function getBeauticianId() {
	$beautician = getBeautician(); 		 	
	return $beautician ['id'];
}

/**
 * @func: 获取后台设置的全局数据
 * @return: array
 */
function getGlobleConfig() {
	$setting = S('GLOBLE_SETTING');
	if (!$setting) {
		$setting = M('_config')->find();
		S('GLOBLE_SETTING', $setting);
	}
	return $setting;
}

/**
 * @func: 格式化服务热线的电话样式
 * @return: string
 */
function format_phone($phone)
{
	$phone = preg_replace("/[^0-9]/", "", $phone);

	if(strlen($phone) == 7)
		return preg_replace("/([0-9]{4})([0-9]{3})/", "$1-$2", $phone);
	elseif(strlen($phone) == 10)
	return preg_replace("/([0-9]{4})([0-9]{3})([0-9]{3})/", "$1-$2-$3", $phone);
	else
		return $phone;
}

function hidden_phone_word($phone) {
	$phone = preg_replace("/[^0-9]/", "", $phone);

	return preg_replace("/([0-9]{3})([0-9]{5})([0-9]{3})/", "$1*****$3", $phone);
}

/**
 * 通过图片的远程url，下载到本地
 * @param: $url为图片远程链接
 * @param: $filename为下载图片后保存的文件名
 */
function GrabImage($url, $dirname, $filename) {
	if($url==""):return false;endif;

	if(!is_dir($dirname)) {
		mkdir($dirname, 0777, true);
	}

	ob_start();
	readfile($url);
	$img = ob_get_contents();
	ob_end_clean();
	$size = strlen($img);

	$fp2=@fopen($dirname.$filename, "a");
	fwrite($fp2,$img);
	fclose($fp2);

	return $filename;
}

/**
 * @func: 微信下载多媒体文件
 * @return: string
 */
function saveMedia($serviceId, $dirname, $img_name = null){
	$access_token = getAccessToken();
	$url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$access_token.'&media_id='.$serviceId;
	
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_NOBODY, 0);    //对body进行输出。
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$package = curl_exec($ch);
	$httpinfo = curl_getinfo($ch);
	 
	curl_close($ch);
	$media = array_merge(array('mediaBody' => $package), $httpinfo);

	if (!$img_name) {
		//求出文件格式
		preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches);
		$fileExt = $extmatches[1];
		$filename = time().rand(100,999).".{$fileExt}";
	} else {
		$filename = $img_name;
	}
	
	if(!file_exists($dirname)){
		mkdir($dirname,0777,true);
	}
	
	file_put_contents($dirname.$filename,$media['mediaBody']);
	return $filename;
}

/**
 * @func: 多维数组排序
 * @return: array
 */
function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
	if(is_array($multi_array)){
		foreach ($multi_array as $row_array){
			if(is_array($row_array)){
				$key_array[] = $row_array[$sort_key];
			}else{
				return false;
			}
		}
	}else{
		return false;
	}
	
	array_multisort($key_array,$sort,$multi_array);
	return $multi_array;
}

/**
 * 短信发送
 * 
 * @param class $class
 * @param string $content
 */
function sendSMS($class, $phone, $content) {
	return $class->send($phone, $content);
}

/**
 * @func: 获取access_token
 * @return: string
 */
function getAccessToken(){
	
	/**
	 * 先判断文件是否存在，如果存在取出时间看有没有过期
	 * 如果过期就再次去获取，没有则用xml文件中的
	 */
	$time = time ();
	$file_path = C ( 'wesetDir' ) . '/lib';
	if (file_exists ( $file_path . "/config/token.xml" )) {
		// 文件存在,解析xml文件取出时间
		$token_arr = ( array ) simplexml_load_file ( $file_path . "/config/token.xml" );
		if (($time - $token_arr ['time']) > C('TOKEN_TIME_OUT_SET')) {
			
			$weixinTokenModel = M('wx_token');
			$tokenRecord = $weixinTokenModel->order('times DESC')->limit(1)->find();
			if (!$tokenRecord || ($time - $tokenRecord ['times'] > C('TOKEN_TIME_OUT_SET'))) {
				// 超时
				// 取出的appid和appsecret
				$xml_path = $file_path . "/config/app.xml";
				if (file_exists ( $xml_path )) {
					$app_xml = ( array ) simplexml_load_file ( $xml_path );
					$appId = $app_xml ['appId'];
					$appSecret = $app_xml ['appSecret'];
				} else {
					return - 1;
					exit ();
				}
				$TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
				$json = file_get_contents ( $TOKEN_URL );
				$result = json_decode ( $json, true );
				$ACC_TOKEN = $result ['access_token'];
				
				$weixinTokenModel->add(array('access_token' => $ACC_TOKEN, 'times' => $time));
				createAccessTokenXml ( $ACC_TOKEN, $time );
			} else if ($tokenRecord) {
				$ACC_TOKEN = $tokenRecord ['access_token'];
				
				createAccessTokenXml ( $ACC_TOKEN, $tokenRecord ['times'] );
			}
		} else {
			// 没有超时
			$ACC_TOKEN = $token_arr ['access_token'];
			
			//验证没过期的二维码是否有效
			$valid = checkAccessTokenValid($ACC_TOKEN,$token_arr ['time']);
			if(empty($valid)){
				//强制刷新
				// 取出的appid和appsecret
				$xml_path = $file_path . "/config/app.xml";
				if (file_exists ( $xml_path )) {
					$app_xml = ( array ) simplexml_load_file ( $xml_path );
					$appId = $app_xml ['appId'];
					$appSecret = $app_xml ['appSecret'];
				} else {
					return - 1;
					exit ();
				}
				$TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
				$json = file_get_contents ( $TOKEN_URL );
				$result = json_decode ( $json, true );
				$ACC_TOKEN = $result ['access_token'];
				
				createAccessTokenXml ( $ACC_TOKEN, $time );
			}
		}
	} else {
		$weixinTokenModel = M('wx_token');
		$tokenRecord = $weixinTokenModel->order('times DESC')->limit(1)->find();
		
		if (!$tokenRecord || ($time - $tokenRecord ['times'] > C('TOKEN_TIME_OUT_SET'))) {
			// 取出的appid和appsecret
			$xml_path = $file_path . "/config/app.xml";
			if (file_exists ( $xml_path )) {
				$app_xml = ( array ) simplexml_load_file ( $xml_path );
				$appId = $app_xml ['appId'];
				$appSecret = $app_xml ['appSecret'];
			} else {
				return - 1;
				exit ();
			}
			
			$TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
			$json = file_get_contents ( $TOKEN_URL );
			$result = json_decode ( $json, true );
			$ACC_TOKEN = $result ['access_token'];
				
			$weixinTokenModel->add(array('access_token' => $ACC_TOKEN, 'times' => $time));
			createAccessTokenXml ( $ACC_TOKEN, $time );
		} else if ($tokenRecord) {
			$ACC_TOKEN = $tokenRecord ['access_token'];
				
			createAccessTokenXml ( $ACC_TOKEN, $tokenRecord ['times'] );
		}
	}
	
	return $ACC_TOKEN;
}

/**
 * 如果accesstoken在有效时间，需要用生成二维马接口验证一个是否是有效
 */
function checkAccessTokenValid($tokens, $t) {
	if (C ( 'isAccessTokenDebuge' )) {
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $tokens;
		
		$scene_id = 88888;
		// 生成永久二维码
		$qrcode = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene_id . '}}}';
		
		$result = https_post ( $url, $qrcode );
		
		$result = json_decode ( $result, true );
		
		date_default_timezone_set ( 'PRC' );
		if (empty ( $result ['ticket'] )) {
			$t1 = $t;
			$t2 = date ( 'Y-m-d H:i:s', $t1 );
			$curTime1 = time ();
			$curTime2 = date ( 'Y-m-d H:i:s', $curTime1 );
			$data = array (
					'accesstoken' => $tokens,
					'accesstime1' => $t1,
					'accesstime2' => $t2,
					'curtime1' => $curTime1,
					'curtime2' => $curTime2,
					'ticket' => $result ['errcode'],
					'url' => $result ['errmsg'] 
			);
			M ( 'wx_test_accesstoken' )->add ( $data );
			
			return false;
		} else {
			$t1 = $t;
			$t2 = date ( 'Y-m-d H:i:s', $t1 );
			$curTime1 = time ();
			$curTime2 = date ( 'Y-m-d H:i:s', $curTime1 );
			$data = array (
					'accesstoken' => $tokens,
					'accesstime1' => $t1,
					'accesstime2' => $t2,
					'curtime1' => $curTime1,
					'curtime2' => $curTime2,
					'ticket' => $result ['ticket'],
					'url' => $result ['url'] 
			);
			M ( 'wx_test_accesstoken' )->add ( $data );
			return true;
		}
	} else {
		return true;
	}
}

/**
 *
 * @param $access_token 存放access_token        	
 * @param $time 存放access_token的时间        	
 */
function createAccessTokenXml($access_token, $time) {
	$doc = new DOMDocument ( "1.0", "utf-8" );
	$doc->formatOutput = true; // 设置可输出操作
	$root = $doc->createElement ( "root" ); // 设置根节点
	$root = $doc->appendChild ( $root ); // 添加根节点
	$name = $doc->createElement ( "access_token" ); // 创建父节点name
	$name = $root->appendChild ( $name ); // 把节点添加到menu节点的子节点
	$name->appendChild ( $doc->createTextNode ( $access_token ) );
	
	$type = $doc->createElement ( "time" ); // 创建父节点name
	$type = $root->appendChild ( $type ); // 把节点添加到menu节点的子节点
	$type->appendChild ( $doc->createTextNode ( $time ) );
	$file_path = C ( 'wesetDir' ) . '/lib';
	$doc->save ( $file_path . "/config/token.xml" );
}
function getApiTicket() {
	/**
	 * 先判断文件是否存在，如果存在取出时间看有没有过期
	 * 如果过期就再次去获取，没有则用xml文件中的
	 */
	$time = time ();
	$file_path = C ( 'wesetDir' ) . '/lib';
	if (file_exists ( $file_path . "/config/api_ticket.xml" )) {
		// 文件存在,解析xml文件取出时间
		$token_arr = ( array ) simplexml_load_file ( $file_path . "/config/api_ticket.xml" );
		if (($time - $token_arr ['time']) > C ( 'TOKEN_TIME_OUT_SET' )) {
			// 超时
			$accessToken = getAccessToken ();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $accessToken . "&type=wx_card";
			$json = httpGet ( $url );
			$result = json_decode ( $json, true );
			$ticket = $result ['ticket'];
			
			createApiTicketXml ( $ticket, $time );
		} else {
			// 没有超时
			$ticket = $token_arr ['ticket'];
		}
	} else {
		
		$accessToken = getAccessToken ();
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $accessToken . "&type=wx_card";
		$json = httpGet ( $url );
		$result = json_decode ( $json, true );
		$ticket = $result ['ticket'];
		createApiTicketXml ( $ticket, $time );
	}
	return $ticket;
}

/**
 *
 * @param $access_token 存放access_token        	
 * @param $time 存放access_token的时间        	
 */
function createApiTicketXml($ticket, $time) {
	$doc = new DOMDocument ( "1.0", "utf-8" );
	$doc->formatOutput = true; // 设置可输出操作
	$root = $doc->createElement ( "root" ); // 设置根节点
	$root = $doc->appendChild ( $root ); // 添加根节点
	$name = $doc->createElement ( "ticket" ); // 创建父节点name
	$name = $root->appendChild ( $name ); // 把节点添加到menu节点的子节点
	$name->appendChild ( $doc->createTextNode ( $ticket ) );
	
	$type = $doc->createElement ( "time" ); // 创建父节点name
	$type = $root->appendChild ( $type ); // 把节点添加到menu节点的子节点
	$type->appendChild ( $doc->createTextNode ( $time ) );
	$file_path = C ( 'wesetDir' ) . '/lib';
	$doc->save ( $file_path . "/config/api_ticket.xml" );
}

/**
 * 得到js-sdk-参数
 * 
 * @return multitype:string NULL number
 */
function getSignPackage() {
	$file_path = C ( 'wesetDir' ) . '/lib';
	$xml_path = $file_path . "/config/app.xml";
	if (file_exists ( $xml_path )) {
		$app_xml = ( array ) simplexml_load_file ( $xml_path );
		$appId = $app_xml ['appId'];
		$appSecret = $app_xml ['appSecret'];
	} else {
		echo "app.xml not found!";
		exit ();
	}
	
	$jsapiTicket = getJsApiTicket ();
	$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	
	$timestamp = time ();
	$nonceStr = createNonceStr ();
	// 这里参数的顺序要按照 key 值 ASCII 码升序排序
	$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	$signature = sha1 ( $string );
	$signPackage = array (
			"appId" => $appId,
			"nonceStr" => $nonceStr,
			"timestamp" => $timestamp,
			"url" => $url,
			"signature" => $signature,
			"rawString" => $string 
	);
	return $signPackage;
}

/**
 * 签名
 * 
 * @param number $length        	
 * @return string
 */
function createNonceStr($length = 16) {
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	$str = "";
	for($i = 0; $i < $length; $i ++) {
		$str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
	}
	return $str;
}
function getJsApiTicket() {
	// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
	// $url_path = dirname(dirname(__FILE__));
	$url_path = C ( 'wesetDir' );
	$json_path = $url_path . "/lib/config/jsapi_ticket.json";
	
	$data = json_decode ( httpGet ( $json_path ) );
	if ($data->expire_time < time ()) {
		
		$accessToken = getAccessToken ();
		$url = "http://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
		$res = json_decode ( httpsGet ( $url ) );
		$ticket = $res->ticket;
		if ($ticket) {
			$data->expire_time = time () + 7000;
			$data->jsapi_ticket = $ticket;
			$fp = fopen ( $url_path . "/lib/config/jsapi_ticket.json", "w" );
			fwrite ( $fp, json_encode ( $data ) );
			fclose ( $fp );
		}
	} else {
		$ticket = $data->jsapi_ticket;
	}
	return $ticket;
}

/**
 * 查询返回appId和appSecret
 */
function getAppIdAndSecret() {
	$file_path = C ( 'wesetDir' ) . '/lib';
	$xml_path = $file_path . "/config/app.xml";
	$appId = '';
	$appSecret = '';
	if (file_exists ( $xml_path )) {
		$app_xml = ( array ) simplexml_load_file ( $xml_path );
		$appId = $app_xml ['appId'];
		$appSecret = $app_xml ['appSecret'];
	}
	
	$arr = array (
			'appId' => $appId,
			'appSecret' => $appSecret 
	);
	
	return $arr;
}
function paylogger($log_content, $log_filename = null) {
	$max_size = 100000;
	$log_dir = C ( 'publicDir' ) . "/log";
	if (empty ( $log_filename )) {
		$log_filename = $log_dir . "/paylog.log"; // log文件路径
	}
	if (! is_dir ( $log_dir )) {
		mkdir ( $log_dir );
		chmod ( $log_dir, 0755 );
	}
	
	if (file_exists ( $log_filename ) and (abs ( filesize ( $log_filename ) ) > $max_size)) {
		unlink ( $log_filename );
	}
	file_put_contents ( $log_filename, date ( 'H:i:s' ) . " " . $log_content . "\r\n", FILE_APPEND );
	// echo abs(filesize($log_filename));
}
